package com.tianji.job;

import cn.hutool.core.collection.CollectionUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.tianji.common.constant.SMSConstant;
import com.tianji.config.XxlConfig;
import com.tianji.coupon.enums.UserCouponStatus;
import com.tianji.coupon.pojo.LogSms;
import com.tianji.coupon.pojo.UserCoupon;
import com.tianji.coupon.service.CouponService;
import com.tianji.coupon.service.LogSmsService;
import com.tianji.coupon.service.UserCouponService;
import com.tianji.login.pojo.SysUser;
import com.tianji.login.service.SysUserService;
import com.tianji.common.utils.SMSUtils;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CouponJob {
    private final Logger log = LoggerFactory.getLogger(XxlConfig.class);

    private final CouponService couponService;

    private final UserCouponService userCouponService;

    private final SysUserService sysUserService;

    private final LogSmsService logSmsService;

    public CouponJob(CouponService couponService
            , UserCouponService userCouponService
            , SysUserService sysUserService
            , LogSmsService logSmsService) {
        this.couponService = couponService;
        this.userCouponService = userCouponService;
        this.sysUserService = sysUserService;
        this.logSmsService = logSmsService;
    }




    //定时开始发放优惠券
    @XxlJob("couponTask")
    public void couponTask() {
        try {
            XxlJobHelper.log("****  定时开始发放优惠券 ****");
            //获取当前分片总数和当前分片索引
            int shardIndex = XxlJobHelper.getShardIndex();
            int shardTotal = XxlJobHelper.getShardTotal();

            //分片处理：每个分片处理部分优惠券数据
            Boolean result = couponService.couponTask(shardIndex, shardTotal);
            if(result){
                XxlJobHelper.log("成功更新分片索引为 "+shardIndex+" 的优惠券状态");
            }else{
                XxlJobHelper.log("成功更新分片索引为 "+shardIndex+" 无优惠券状态需要更新");
            }
        } catch (Exception e) {
            XxlJobHelper.log("更新优惠券状态时出错: "+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    //定时开始检查过期优惠券
    @XxlJob("couponExpire")
    public void couponExpire() {
        try {
            XxlJobHelper.log("**** 定时开始检查过期优惠券 ****");
            int shardTotal = XxlJobHelper.getShardTotal();
            int shardIndex = XxlJobHelper.getShardIndex();
            List<UserCoupon> list = userCouponService.lambdaQuery()
                    .le(UserCoupon::getTermEndTime, LocalDateTime.now())
                    .eq(UserCoupon::getStatus, UserCouponStatus.UNUSED.getValue())
                    .list();
            if(CollectionUtil.isNotEmpty(list)){
                List<Long> collect = list.stream().map(UserCoupon::getUserId).collect(Collectors.toList());
                List<SysUser> list1 = sysUserService.lambdaQuery()
                        .in(SysUser::getUserId, collect).list();
                if(CollectionUtil.isNotEmpty(list1)){
                    for(SysUser sysUser:list1){
                        String phoneNumber = sysUser.getPhone();
                        String message = "你有一张优惠券已经过期，请注意查看";
                        String smsFunc = "couponExpire";
                        String smsReturnCode;
                        try {
                            // 调用发送短信接口并获取返回值
                            SendSmsResponse response = SMSUtils.sendMessage(phoneNumber,
                                    SMSConstant.signName, SMSConstant.CodeTemplate, message);
                            // 获取状态码
                            int statusCode = response.getStatusCode();
                            smsReturnCode = statusCode == 200 ? "Success" : "Failure: " + statusCode;
                            // 获取更多的返回信息（如果需要）
                            SendSmsResponseBody body = response.getBody();
                            String requestId = body.getRequestId();
                            String bizId = body.getBizId();
                            // 打印日志或处理额外的信息（可选）
                            XxlJobHelper.log("短信发送请求ID: " + requestId + ", 业务ID: " + bizId);
                        } catch (Exception e) {
                            smsReturnCode = "Failure: " + e.getMessage();
                            XxlJobHelper.log("短信发送失败: " + e.getMessage());
                        }
                        // 记录日志到 log_sms 表
                        LogSms logSms = new LogSms();
                        logSms.setSmssrc(1);
                        logSms.setSmsuserid(sysUser.getUserId());
                        logSms.setSmscontent(message);
                        logSms.setSmsphonrnumber(phoneNumber);
                        logSms.setSmsreturncode(smsReturnCode);
                        logSms.setSmscode("");
                        logSms.setSmsfunc(smsFunc);
                        logSms.setCreatetime(LocalDateTime.now());
                        // 异步保存日志
                        logSmsService.saveAsync(logSms);
                    }
                }
                userCouponService.lambdaUpdate()
                        .set(UserCoupon::getStatus, UserCouponStatus.EXPIRED.getValue())
                        .set(UserCoupon::getUpdateTime, LocalDateTime.now())
                        .le(UserCoupon::getTermEndTime, LocalDateTime.now())
                        .in(UserCoupon::getUserId, collect)
                        .last("and mod(id,"+shardTotal+") = "+shardIndex)
                        .update();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
